﻿using System;
using dotNetMagazin201108.BusinessLayer;
using Microsoft.SharePoint.Client;

namespace dotNetMagazin201108.PersistenceLayer
{
    public class SharePointCompanyRepository : SharePointBaseRepository, CompanyRepository
    {
        private const string SharePointListNameCompanies = "Companies";

        public System.Collections.Generic.IEnumerable<Company> GetAll()
        {
            var context = CurrentContext;

            List companies = context.Web.Lists.GetByTitle(SharePointListNameCompanies);
            ListItemCollection items = companies.GetItems(new CamlQuery());
            
            context.Load(items);
            context.ExecuteQuery();

            foreach (ListItem i in items)
            {
                yield return new Company() 
                { 
                    Id = i.Id, 
                    Name=(string)i["Title"], 
                    Size=(int)((double)i["Size"]) // unboxing and casting 
                };
            }
        }

        public Company GetById(int id)
        {
            throw new NotImplementedException();
        }

        public bool Add(Company entity)
        {
            var context = CurrentContext;
            List companies = context.Web.Lists.GetByTitle(SharePointListNameCompanies);
            ListItemCreationInformation listCI = new ListItemCreationInformation();

            ListItem company = companies.AddItem(listCI);
            company["Title"] = entity.Name;
            company["Size"] = (double)entity.Size;
            company.Update();
            context.ExecuteQuery();

            entity.Id = company.Id;

            return true;
        }

        public bool Update(Company entity)
        {
            throw new NotImplementedException();
        }
    }
}
